import axios from "axios"
import { ElMessage } from "element-plus"
import tool from "@/utils/tools"
// import qs from "qs"
import { get, isEmpty } from "lodash"

function createService() {
  // 创建一个 axios 实例
  const service = axios.create()

  // HTTP request 拦截器
  service.interceptors.request.use(
      (config) => config,
      (error) => {
        console.log("error", error)
        // 失败
        return Promise.reject(error)
      }
  )

  // HTTP response 拦截器
  service.interceptors.response.use(
      (response) => {
        // if ((response.headers['content-disposition'] || ! /^application\/json/.test(response.headers['content-type'])) && response.status === 200) {
        //   return response
        // } else if (response.data.size) {
        //   response.data.code = 500
        //   response.data.message = '服务器内部错误'
        //   response.data.success = false
        // } else if (response.data.code && response.data.code !== 200) {
        //   ElMessage({
        //     message: response.data.msg,
        //     type: "error",
        //   })
        // }
        if (response.status === 200) {
          switch (response.data.status) {
              // 登录失效
              // case 410000:
              //   ElMessage({
              //     message: response.data.msg,
              //     type: "error",
              //     onClose: () => {
              //       window.localStorage.clear()
              //       window.location.href = `/login?redirect=${window.location.pathname}`
              //     }
              //   })
              //   break
              // case 410002:
              //   ElMessage({
              //     message: response.data.msg,
              //     type: "error",
              //     onClose: () => {
              //       window.localStorage.clear()
              //       window.location.href = `/login?redirect=${window.location.pathname}`
              //     }
              //   })
              //   break
            case 400:
              // 如果是登录接口则不弹窗，按实际情况处理
              if (response.config.url.indexOf("api/v2/check/login") === -1) {
                ElMessage({
                  message: response.data.msg,
                  type: "error"
                })
              }
              break
          }
          return response.data
        } else {
          ElMessage({
            message: response.data.msg,
            type: "error",
          })
        }
        return response.data
      },
      (error) => {
        const err = (text) => {
          ElMessage({
            message: error.response && error.response.data && error.response.data.msg ? error.response.data.msg : text,
            type: "error"
          })
        }
        if (error.response && error.response.data) {
          switch (error.response.status) {
            case 404:
              err("服务器资源不存在")
              break
            case 500:
              err("服务器内部错误")
              break
            case 401:
              err("登录状态已过期，需要重新登录")
              tool.local.clear()
              window.location.href = `/login?redirect=${window.location.pathname}`
              break
            case 403:
              err("没有权限访问该资源")
              break
            default:
              err("未知错误！")
          }
        } else {
          err("请求超时，服务器无响应！")
        }
        return Promise.reject(error.response && error.response.data ? error.response.data : null)
      }
  )
  return service
}

function stringify(data) {
  return qs.stringify(data, { allowDots: true, encode: false })
}

/**
 * @description 创建请求方法
 * @param {Object} service axios 实例
 */
function createRequest(service) {
  return function (config) {
    const env = import.meta.env
    const requestType = config.type
    const token = tool.local.get(env.VITE_APP_TOKEN_PREFIX)
    const configDefault = {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": get(config, "headers.Content-Type", "application/json;charset=UTF-8")
      },
      timeout: 100000,
      baseURL: env.MODE === "dev" ? "/apiProxy" : requestType === 'admin' ? env.VITE_APP_ADMIN_URL : env.VITE_APP_BASE_URL,
      data: {}
    }
    // configDefault.headers["Authori-zation"] = `Bearer ${token}`
    const option = Object.assign(configDefault, config)

    // json
    // if (!isEmpty(option.params)) {
    //   option.url = option.url + '?' + stringify(option.params)
    //   option.params = {}
    // }

    return service(option)
  }
}
const service = createService()
export default createRequest(service)
